<template>
  <div class="app-container">
    <div class="search-container">
      <div class="button-container">
        <el-button :disabled="true" type="danger"><el-icon>
            <Plus />
          </el-icon>&nbsp;新增</el-button>
        <el-button :disabled="false" type="danger" @click="submitForm(ruleFormRef)"><el-icon>
            <Plus />
          </el-icon>&nbsp;保存</el-button>
        <el-button :disabled="false" type="danger"><el-icon>
            <Plus />
          </el-icon>&nbsp;撤销</el-button>
        <el-button :disabled="true" type="danger"><el-icon>
            <Plus />
          </el-icon>&nbsp;删除</el-button>
      </div>
      <el-form ref="ruleFormRef" style="max-width: 600px;margin-top: 20px;" :model="form" :rules="rules"
        label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="转种日期" prop="dateOfPurchase">
              <el-date-picker v-model="form.descendantDate" type="date" placeholder="请选择转种日期" clearable
                :value-format="'YYYY-MM-DD HH:mm:ss'" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="单据号"> — — </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="流水号"> — — </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="select">
      <el-table :data="datatable" stripe style="width: 100%;height: 500px;">
        <el-table-column prop="earTag" label="育成羊耳号" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.earTag" placeholder="请选择耳号" @change="detilLambWean()">
              <el-option :label="item.earTag" :value="item.earTag" v-for="item in ererars" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="descendantSex" label="性别" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.descendantSex" placeholder="请选择性别" @change="getIdHouse()">
              <el-option label="公" :value="true" />
              <el-option label="母" :value="false" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="currentBuilding" label="当前栋舍" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.currentBuilding" placeholder="请选择栋舍ID"
              @change="getcolumnIdList(scope.row.currentBuilding)" :disabled="true">
              <el-option :label="item.ridgepoleName" :value="item.ridgepoleId" v-for="item in buildingIdList" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="currentField" label="当前栏位" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.currentField" placeholder="请选择栏位ID" :disabled="true">
              <el-option :label="item.columnName" :value="item.columnManagementId" v-for="item in columnIdList" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="toBuildingManageId" label="转入栋舍" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.toBuildingManageId" placeholder="请选择栋舍ID"
              @change="getcolumnIdLists(scope.row.toBuildingManageId)">
              <el-option :label="item.ridgepoleName" :value="item.ridgepoleId" v-for="item in idHouse" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="toColumMangementId" label="转入栏位" width="140">
          <template #default="scope" prop="toColumMangementId">
            <el-select v-model="scope.row.toColumMangementId" placeholder="请选择栏位ID">
              <el-option :label="item.columnName" :value="item.columnManagementId" v-for="item in columnIdLists" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="count">
      <span style="float: left"> 合计 </span>
      <span style="float: right"> 0.00 </span>
    </div>
    <div class="count1">
      <el-button link type="danger" @click="Addform()"> + 增行 </el-button>
      <el-button link type="danger" @click="Deleteform()"> - 删行 </el-button>
    </div>
    <div class="count2">
      <el-form ref="ruleFormRef" :model="form" label-width="auto" class="demo-ruleForm" status-icon>
        <el-form-item label="备注">
          <el-input type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import transfer from '@/api/ProgenyTransferment/index'
import sheepfile from '@/api/ProductionManagement/index'
import purcure from '@/api/PurchaseMent/index'
import { purcoreQuery, buildingIdQuery } from '@/api/PurchaseMent/model'
import LambWean from '@/api/Ablactationment/index'
import { useRoute } from 'vue-router'
const route = useRoute()
//参数
const form = reactive({
  descendantDate: "2024-02-02"
})
const datatable = reactive([{
  "descendantId": null,
  "earTag": "",
  "descendantDate": "2024-02-02",
  "toBuildingManageId": null,
  "toColumMangementId": null,
  "currentBuilding": null,
  "currentField": null,
  "descendantSex": null,
  "createName": "",
  "createTime": "2024-02-02",
  "updateName": "",
  "updateTime": "2024-02-02",
  "isDel": false
}])
const c = ref(0);
//增行
const Addform = () => {
  c.value = 1;
  datatable.forEach((item) => {
    c.value++;
  });
  datatable.push({
    "descendantId": null,
    "earTag": "",
    "toBuildingManageId": null,
    "toColumMangementId": null,
    "currentBuilding": null,
    "currentField": null,
    "descendantSex": null,
    "createName": "",
    "createTime": "2024-02-02",
    "updateName": "",
    "updateTime": "2024-02-02",
    "isDel": false
  });
};
//删行
const Deleteform = () => {
  datatable.pop();
};
//反填
const fuii = () => {
  transfer.ftDescend(route.query.eartag).then(res => {
    datatable.forEach(c => {
      c.earTag = res.data.earTag
      c.descendantSex = res.data.descendantSex
      if (c.descendantSex == true) {
        LambWean.getHouse(5).then(ress => {
          getIdHouse()
          c.toBuildingManageId = ress.data[0].ridgepoleId

          console.log(c.toBuildingManageId)
          getcolumnIdLists(ress.data[0].ridgepoleId)
          c.toColumMangementId = res.data.toColumMangementId
          getBuildingIdList()
          c.currentBuilding = res.data.currentBuilding
          c.descendantId = res.data.descendantId
          getcolumnIdList(c.currentBuilding)
          c.currentField = res.data.currentField
          c.createName = res.data.createName
          c.createTime = res.data.createTime
          c.updateName = res.data.updateName
          c.updateTime = res.data.updateTime
          c.isDel = res.data.isDel
        })
        c.toColumMangementId = null
        c.currentBuilding = null
      }
      else {
        c.toColumMangementId = null
        c.currentBuilding = null
        LambWean.getHouse(1).then(ress => {
          getIdHouse()
          c.toBuildingManageId = ress.data[0].ridgepoleId
          getcolumnIdLists(c.toBuildingManageId)
          c.toColumMangementId = res.data.toColumMangementId
          getBuildingIdList()
          c.currentBuilding = res.data.currentBuilding
          c.descendantId = res.data.descendantId
          getcolumnIdList(c.currentBuilding)
          c.currentField = res.data.currentField

          c.createName = res.data.createName
          c.createTime = res.data.createTime
          c.updateName = res.data.updateName
          c.updateTime = res.data.updateTime
          c.isDel = res.data.isDel
        })
      }
    })
    form.descendantDate = res.data.descendantDate
  })
}
//表单
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  weaningDate: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      datatable.forEach((item: any) => {
        item.descendantDate = form.descendantDate
      });
      // 将数组转换为字符串
      let jsonString = JSON.stringify(datatable);

      // 去掉开头和结尾的中括号
      let stringWithoutBrackets = jsonString.slice(1, -1);
      transfer.updateDescend(stringWithoutBrackets).then(res => {
        console.log(res)

        ElMessage.success('添加成功')

      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//反填耳号
const detilLambWean = async () => {
  for (let item of datatable) {
    try {
      const res = await sheepfile.detilsheepfile(item.earTag);

      item.earTag = res.data.earTag;
      getBuildingIdList();
      item.currentBuilding = res.data.buildingId;

      getcolumnIdList(item.currentBuilding);
      item.currentField = res.data.columnId;
    } catch (error) {
      console.error('Error fetching data for earTag:', item.earTag, error);
    }
  }
};
//获取耳号
const ererars = ref([])
const getSheepfaears = () => {
  const form = reactive({
    presentState: 1,
    sheepType: 3,
    growthstage: 2
  })
  sheepfile.grothshrrpfile(form.presentState, form.sheepType, form.growthstage).then(res => {
    ererars.value = res.data
  })
}
//获取栋舍
const forms = reactive<buildingIdQuery>({
  "pageIndex": 1,
  "pageSize": 100,
  "ridgepoleTypeId": 0,
  "ridgepoleName": "",
  "responsiblePerson": ""
})

const buildingIdList: any = ref([])
const getBuildingIdList = () => {

  purcure.getrid(forms).then((res: any) => {
    buildingIdList.value = res.data.data
  })
}
//获取栏位
const columnIdList: any = ref([])
const getcolumnIdList = (id: any) => {
  console.log(id)
  purcure.getcolumn(id).then((res: any) => {
    columnIdList.value = res.data
    console.log(columnIdList.value)
  })
  columnIdList.value = []
}
//根据id获取栋舍
const idHouse = ref([])
const getIdHouse = () => {
  datatable.forEach(c => {

    //公
    if (c.descendantSex == true) {
      LambWean.getHouse(5).then(res => {
        idHouse.value = res.data
      })
    }
    else {
      LambWean.getHouse(1).then(res => {
        idHouse.value = res.data
      })
    }

  })
}
//获取栏位
const columnIdLists: any = ref([])
const getcolumnIdLists = (id: any) => {
  console.log(id)
  purcure.getcolumn(id).then((res: any) => {
    columnIdLists.value = res.data
    console.log(columnIdLists.value)
  })
  columnIdLists.value = []
}
onMounted(() => {
  getBuildingIdList()
  getSheepfaears()
  detilLambWean()
  getIdHouse()
  fuii()
})
</script>